package main

import (
	"fmt"
	"gitee.com/wayjin/fabric-extension/cryptoutil/caclient"
	"gitee.com/wayjin/fabric-extension/tools/cryptogenv2/api"
	"github.com/spf13/cobra"
)

var (
	configFile string
	caURL  string
	authPath string
	mspCAName string
	tlsCAName string
	idType string
	idName string
	idSecret string
	affiliation string
	idAttrs string
	output string
	serverPort  int
)

var (
	client *caclient.Client
)

var rootCmd = &cobra.Command{}

var generateCmd = &cobra.Command{
	Use: "generate",
	Short: "generate crypto certs",
	Run:generateCommand,
}

var serverCmd = &cobra.Command{
	Use:   "serve",
	Short: "server api for customer interface",
	Run:   serverCommand,
}

var versionCmd = &cobra.Command{
	Use: "version",
	Short: "show version of cryptogenv2",
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("1.4.x")
	},
}

func init() {
	generateCmd.Flags().StringVarP(&configFile, "config", "f", "", "config file for generate cryptocerts")
	generateCmd.Flags().StringVarP(&caURL, "ca.url", "u", "", "CA server http address")
	generateCmd.Flags().StringVarP(&mspCAName, "caname.msp", "", "", "")
	generateCmd.Flags().StringVarP(&tlsCAName, "caname.tls", "", "", "")
	generateCmd.Flags().StringVarP(&idType, "id.type", "", "", "type of identity, eg 'peer','orderer','admin','client'")
	generateCmd.Flags().StringVarP(&idName, "id.name", "", "", "name of identity")
	generateCmd.Flags().StringVarP(&idSecret, "id.secret", "", "password123", "secret of identity")
	generateCmd.Flags().StringVarP(&idAttrs, "id.attrs", "", "", "A list of comma-separated attributes of the form <name>=<value> (e.g. foo=foo1,bar=bar1)")
	generateCmd.Flags().StringVarP(&affiliation, "id.affiliation", "", "", "affiliation of identity that belong to organizations")
	generateCmd.Flags().StringVarP(&authPath, "auth", "", "", "admin cryptocert path that authorize to be register")
	generateCmd.Flags().StringVarP(&output, "output", "o", "crypto-config", "")
	serverCmd.Flags().IntVarP(&serverPort, "port", "p", 9690, "")
	rootCmd.AddCommand(generateCmd)
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(serverCmd)
}

func generateCommand(cmd *cobra.Command, args []string) {
	err := generate()
	if err != nil {
		fmt.Println(err)
	}
}

func generate() error {
	var err error
	if configFile != "" {
		err = api.GenerateFromConfig(configFile, caURL, output)
		if err != nil {
			return fmt.Errorf("fail to generate: %v", err)
		}
	}
	if idName != "" {
		if idType == "" {
			return fmt.Errorf("id type and secret is required")
		}

		nodeID := api.NodeIdentity{Name:idName, Secret:idSecret, Affiliation: affiliation,Type:api.NodeType(idType), Attrs:idAttrs}
		err = nodeID.Generate(caURL, authPath, output)
		if err != nil {
			return fmt.Errorf("fail to generate: %v", err)
		}
	}
	return nil
}

func serverCommand(cmd *cobra.Command, args []string) {
	// TODO
}

func main() {
	rootCmd.Execute()
}

